<?php
namespace JsonRpc\Services\System;
use Illuminate\Support\Facades\DB;
use JsonRpc\Models\SysRole;
use JsonRpc\Models\SysRoleUser;
use JsonRpc\Models\SysUser;
use JsonRpc\Services\BaseService;
use JsonRpc\Services\CommonService;
use JsonRpc\Utils\Utils;

/**
 *  用户
 * @author walkor <worker-man@qq.com>
 */
class RoleService extends BaseService
{
    use CommonService;

    private static function getBaseModel(){
        return "JsonRpc\\Models\\Sysrole";
    }

    public static function ping(){
        return 'OK';
    }

   static function saveData($params){
        if(isset($params['id']) && $params['id']){
            //更新
            $model = SysRole::find($params['id']);

        }else{
            //新增
            unset($params['id']);
            $model = new SysRole();
            $model->client_id = 1;
            $model->org_id = 1;
        }
       $model->name = $params['name'];
       $model->permission = $params['permission'];
       $model->created_by = $params['created_by'];
       $model->description = $params['description'];
       $model->is_active = $params['is_active'];
       return $model->save();
    }

    public function getInfoList1(){
        $arr = SysUser::get();
        if($arr){
            return $arr->toArray();
        }
        return [];
    }

    public function roleCheck($params){
        $rs = SysRoleUser::where('role_id',$params['id'])->get();
        if($rs){
            $rs1 = $rs->toArray();
            $user_id = array_column($rs1, 'user_id');
            return $user_id;
        }
        return [];
    }
    public function roleCheck1($params){
        $rs = SysRoleUser::where('role_id',$params['id'])->get();
        if($rs){
            $rs1 = $rs->toArray();
            $role_id = array_column($rs1, 'id');
            return $role_id;
        }
        return [];
    }
    public function delAdd($params){
        if(!empty($params['id'])){
            self::beginTransaction();
            try{
                //删除对应用户拥有的权限
                SysRoleUser::where('role_id',$params['id'])->delete();
                    $user = UserService::getInfoById(['id'=>$params['curr_user_id']]);
                    $data = $params['checkbox'];
                    foreach($data as $key => $user_id){
                        $model = new SysRoleUser();
                        $model->client_id = $user['client_id'];
                        $model->org_id = $user['org_id'];
                        $model->created_by = $user['id'];
                        $model->updated_by = $user['id'];

                        $model->role_id = $params['id'];
                        $model->user_id = $user_id;
                        $model->save();
                    }
                self::commit();
                return true;
            }catch (\Exception $e) {
                self::rollBack();
                return false;
            }
        }else{
            return false;
        }
    }
}
